/*
*	控制器类
*	getData(type) return：source	（type=1 国家级数据		type=2 省级数据		type=3 城市级数据）
*	
*/
var Control = {
	loading:false,
	//获取当前日期+请求国家级数据+渲染国家级视图
	init : function(){
		TimelineView.initTime();
		Control.getData(1,function(){
		    View.renderCountry();
		    if ( !checkEmptyObject(CountryModel.source) ) {
		        MapModel.province = CountryModel.source[0][0];
		    }
			CardView.init();
		});
	},
	//请求数据
	getData : function(type,callback){
		if(type==1){
			if( !CountryModel.checkCache( MapModel.date ) ){
				//不存在,动态请求
			    ajax("/Home/CountryData?dateTime=" + MapModel.date, function (data) {
			        CountryModel.add(MapModel.date, eval(data));
			        callback();
			    });
			    //var _result = getMockCountry();
			    //CountryModel.add(MapModel.date, _result);
			    //callback();
			}
			else{
				//存在，调用CountryModel.replace(date)
			    CountryModel.replace(MapModel.date);
			    callback();
			}
		}
		else if(type==2){
			if( !ProvinceModel.checkCache( MapModel.date ) ){
				//todo: ajax请求数据，调用ProvinceModel.add
			    ajax("/Home/ProvinceData?dateTime="+MapModel.date+"&provinceName="+MapModel.province,function(data){
			        ProvinceModel.add(MapModel.date, eval(data));
			       callback();
				})
				//var _result = getMockProvince();
				//ProvinceModel.add(MapModel.date, _result);
				//callback();
			}
			else{
				//存在，调用ProvinceModel.replace(date)
			    ProvinceModel.replace(MapModel.date);
			    callback();
			}
		}
		else{
		    //todo:ajax请求数据
		    var str = "/Home/CityData?dateTime=" + MapModel.date + "&provinceName=" + MapModel.province+"&cityName="+MapModel.city
			ajax(str,function(data){
			    CityModel.add(eval(data));
			    callback();
			});
			//var _result = getMockCity();
			//CityModel.add(_result);
			//callback();
		}
	},
	//切换至省级数据视图
	toProvince : function(_name){
		MapModel.zoom = 7;
		var province_name;
		if(_name==undefined || _name == null ){
			province_name = event.target.parentElement.querySelector("#info-name").innerText;
		}
		else{
			province_name = _name;
		}
		Cache.hideProvincePly();
		Cache.hideCountryPly();
		MAP.closeInfoWindow();
		View.renderProvince(province_name);
	},
	toCity : function(_name){
		MapModel.zoom = 9;
		var city_name;
		if( _name==undefined || _name==null ){
			city_name = event.target.parentElement.querySelector("#info-name").innerText;
		}
		else{
			city_name = _name;
		}
		MapModel.city = city_name;
		console.log("toCity" + city_name);
		MAP.clearOverlays();
		View.renderCity(city_name);
	},
	//新数据加载并基于当前缩放比渲染
	loadNewData : function(){
		//点击查看详情、滑动、点击省级 都可以通过这个来做（点击省级直接用ply缓存比较方便）
		var type = 1;
		//根据type控制ply渲染
		switch(MapModel.zoom){
			case 7:type=2;break;
			case 9:type=3;break;
			default:type=1;break;
		}
		//请求数据
		this.getData(type,function(){
			var i,j,k;
			var data,color;
			if(type==1){
			    //province_ply缓存
			    if ( checkEmptyObject(Cache.province_ply)  ) {
			        View.renderCountry();
//			        console.log(CountryModel.source[0][0]);
			        if ( !checkEmptyObject(CountryModel.source) ) {
			            MapModel.province = CountryModel.source[0][0];
			            //console.log(MapModel.province);
			        }
			        CardView.init();
			    }
			    else {
			        for (var k in Cache.province_ply) {
			            data = CountryModel.getProvinceData(k);
			            if (data == false) {
			                //不存在数据则透明色
			                for (i = 0; i < Cache.province_ply[k].length; i++) {
			                    Cache.province_ply[k][i].setFillColor("transparent");
			                }
			            }
			            else {
			                color = MapModel.getDBColor(data);
			                for (i = 0; i < Cache.province_ply[k].length; i++) {
			                    Cache.province_ply[k][i].setFillColor(color);
			                }
			            }
			        }
			    }
			}
			else if(type==2){
				var i,j,k;
				var data,color;
				//省级数据已经通过外部的this.getData异步获取	这里只需要更新视图即可
				for(var k in Cache.city_ply){
					data = ProvinceModel.getCityData(k);
					if(data==false){
						//不存在数据则透明
						for(i=0;i<Cache.city_ply[k].length;i++){
							Cache.city_ply[k][i].setFillColor("transparent");
						}
					}
					else{
						color = MapModel.getDBColor(data);
						for(i=0;i<Cache.city_ply[k].length;i++){
							Cache.city_ply[k][i].setFillColor(color);
						}
					}
				}
			}
			else{
				Control.toCity(MapModel.city);
			}
			//关闭信息板+重置数据面板
			MAP.closeInfoWindow();
			if(type==1){
				CardView.init();
			}
			else{
				CardView.init(true);
			}
		})
	}
};





/*
*	入口函数
*/
window.onload = function(){
	//地图初始化
	MAP = new BMap.Map("allmap");
	MAP.clearOverlays();
	MAP.centerAndZoom(new BMap.Point(MapModel.center[0],MapModel.center[1]),MapModel.zoom);
	MAP.disableScrollWheelZoom();
	MAP.disableDoubleClickZoom();
	MAP.setMapStyle({styleJson:MapModel.style});
	document.onselectstart=new Function("event.returnValue=false;");
	//数据初始化
	Control.init();
	//初始化时间拖拽控件
	TimelineView.startDrag("dragger","dragger");
}


/*
*	AJAX
*/
function ajax(url, fnSucc, fnFaild){
    //1.创建对象
    var oAjax = null;
    if(window.XMLHttpRequest){
        oAjax = new XMLHttpRequest();
    }else{
        oAjax = new ActiveXObject("Microsoft.XMLHTTP");
    }
      
    //2.连接服务器  
    oAjax.open('GET', url, true);   //open(方法, url, 是否异步)
    
    //3.发送请求  
    oAjax.send();
      
    //4.接收返回
    oAjax.onreadystatechange = function(){  //OnReadyStateChange事件
        if(oAjax.readyState == 4){  //4为完成
            if(oAjax.status == 200){    //200为成功
                fnSucc(oAjax.responseText) 
            }else{
                if(fnFaild){
                    fnFaild();
                }
            }
        }
    };
}
/*
*	{}判断函数
*/
function checkEmptyObject(obj) {
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            return false;
        }
    }
    return true;
}
/*
*	downLoad函数  下载该缩放级别&日期对应的数据
*/
function downLoad() {
    var url = "/Home/Download";
    var param = "";
    var link = document.getElementById("download-btn");
    var zoom = MapModel.zoom;
    if (zoom == 5) {
        if (CountryModel.source.length!=0) {
            param = "?type=1&dateTime=" + MapModel.date;
        }
    }
    else if (zoom == 7) {
        if (ProvinceModel.source.length != 0) {
            param = "?type=2&provinceName=" + MapModel.province + "&dateTime=" + MapModel.date;
        }
    }
    else {
        if (CityModel.source.length != 0) {
            param = "?type=3&provinceName=" + MapModel.province + "&cityName=" + MapModel.city + "&dateTime=" + MapModel.date;
        }
    }
    //Open link
    if (param == "") {
        alert("对不起，当前日期和区域条件下无数据。");
        event.preventDefault();
        return false;
    }
    else {
        link.href = url + param;
        return true;
    }
}